import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/user_entity.dart';
import 'package:shopping_group/utils/log_util.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'dart:convert' as convert;
import 'dart:js' as js;

class UserLoginBloc implements BlocBase {
  //处理登录按钮操作
  StreamController<Object> _cilkeLoginController = StreamController<Object>();

  // 处理登录数据
  StreamController<Object> _loginController = StreamController<Object>();

  //获得微信openid
  StreamController<Object> _openidController = StreamController<Object>();
  StreamSink<Object> get _startLogin => _loginController.sink;
  Stream<Object> get pushDate => _loginController.stream;

  //接收登录按钮点击
  StreamSink get cilkeLoginAction => _cilkeLoginController.sink;
  StreamSink get openidAction => _openidController.sink;

  StreamController<Object> _adduserController = StreamController<Object>();
  StreamSink get addUserAction => _adduserController.sink;

  UserLoginBloc() {
    _cilkeLoginController.stream.listen(loginTask);
    _openidController.stream.listen(openIdTask);
    _adduserController.stream.listen(addUserTask);
  }

  void addUserTask(data) {
    _loginUser(data);
  }

  void openIdTask(data) {
    _getOpenId();
  }

  void loginTask(data) {
    if (data is Map<String, dynamic>) {
      _login(data);
    }
  }

  // 获得openId
  Future _getOpenId() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        Map<String, dynamic> data = new Map<String, dynamic>();
        String ecurl = Uri.encodeComponent('${Apis.WEB_URL}?type=gzhUrl');
        String reUrl = 'redirect_url=$ecurl';

        String url = Apis.WEIXIN_GZH_OPENID_URL +
            '?appid=${BaseConstant.WX_GZH_APPID}&$reUrl&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
        HttpUtilAll.get(url, data: data, headers: {}, success: (result) {
          // 请求成功返回的数据
          if (null != result) {
            // var jsonRes = json.decode(result);
            //Map<String, dynamic> map = Map.from(jsonRes);
            // AccessTokenEntity accessTokenEntity =
            //     AccessTokenEntity.fromJson(map);
            // LogUtil.e(accessTokenEntity.toJson(),
            //     tag: 'WEIXIN_OPENID_URL ...........');
            // if (ObjectUtil.isEmptyString(accessTokenEntity.errcode)) {
            //   String access = accessTokenEntity.accessToken;
            //   String openId = accessTokenEntity.openid;
            //   _getUserInfo(access, openId);
            // } else {
            //   BotToast.closeAllLoading();
            //   BotToast.showText(text: accessTokenEntity.errmsg);
            // }
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // 获得用户信息
  void _getUserInfo(String access, String openid) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        //  BotToast.showLoading();
        Map<String, dynamic> data = {};
        data['access_token'] = access;
        data['openid'] = openid;
        HttpUtilAll.get(Apis.WEIXIN_USRE_URL, data: data, headers: {},
            success: (result) {
          // 请求成功返回的数据
          // if (null != result) {
          //   var jsonRes = json.decode(result);
          //   Map<String, dynamic> map = Map.from(jsonRes);
          //   WXUserInfoEntity wxUserInfoEntity = WXUserInfoEntity.fromJson(map);
          //   if (ObjectUtil.isEmptyString(wxUserInfoEntity.errcode)) {
          //     BaseConstant.wxOpenid = wxUserInfoEntity.openid;
          //     BaseConstant.wxHeadurl = wxUserInfoEntity.headimgurl;
          //     BaseConstant.wxNickname = wxUserInfoEntity.nickname;
          //     // LogUtil.e(userEntity.toJson(), tag: 'UserEntity ...........');
          //     _relaLogin(BaseConstant.PD_LT_WX, openid);
          //   } else {
          //     BotToast.closeAllLoading();
          //     BotToast.showText(text: wxUserInfoEntity.errmsg);
          //   }
          // }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // 获得用户信息
  void _relaLogin(String relaLoginType, String openid) async {
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        //  BotToast.showLoading();
        Map<String, dynamic> data = {};
        data['relaLoginType'] = relaLoginType;
        data['bindWxOpenId'] = openid;
        HttpUtilAll.post(Apis.RELOGIN_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          BotToast.showText(text: '登录成功');
          // 请求成功返回的数据
          if (null != result) {
            // LogUtil.e(userEntity.toJson(), tag: 'UserEntity ...........');
            _loginUser(result);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // 登录
  Future _login(data) async {
    BotToast.showLoading();
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        // Map<String, dynamic> data = new Map<String, dynamic>();
        // data['imgVerifyCode'] = 'AUTO_PASS';
        // data['password'] = Md5Util.generateMd5(data['password']);
        HttpUtilAll.post(Apis.LOGIN_URL,
            data: data,
            headers: {'token': BaseConstant.token}, success: (result) {
          BotToast.closeAllLoading();
          // 请求成功返回的数据
          BotToast.showText(text: '登录成功');
          if (null != result) {
            SharedPreferencesUtil.addShare('password', data['pwd']);
            _loginUser(result);
          }
          RouteUtil.closeView();
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _loginUser(result) {
    UserEntity userEntity = UserEntity.fromJson(result);
    LogUtil.e(userEntity.toJson(), tag: 'UserEntity ...........');
    SharedPreferencesUtil.addShare(
        'userEntity', convert.jsonEncode(userEntity.toJson()));
    BaseConstant.name = userEntity.name;
    BaseConstant.nickname = userEntity.nickname;
    BaseConstant.phone = userEntity.phone;
    BaseConstant.capitalAccount = userEntity.capitalAccount;
    BaseConstant.integralAccount = userEntity.integralAccount;
    BaseConstant.allAccount = userEntity.allAccount;
    BaseConstant.dsAllAcct = userEntity.dsAllAcct;
    BaseConstant.idCard = userEntity.idCard;
    BaseConstant.code = userEntity.code;
    BaseConstant.reBuyQuanAcct = userEntity.reBuyQuanAcct;
    BaseConstant.token = userEntity.token;
    SharedPreferencesUtil.addShare('userName', userEntity.code);
    SharedPreferencesUtil.addShare('nickname', userEntity.nickname);
    SharedPreferencesUtil.addShare('userId', userEntity.userId);
    BaseConstant.weixinOperId = userEntity.weixinOperId;
    // js.context.callMethod('flutterAlert', [BaseConstant.weixinOperId]);
    BaseConstant.userId = userEntity.userId;
    BaseConstant.isRealNameAuthen = 'Y' == userEntity.realNameState;
    BaseConstant.isLogin = true;
    eventBus.fire(BlackEvent());
    eventBus.fire(BlackPageEvent());
    eventBus.fire(BlackForumEvent());
    eventBus.fire(BlackMoreEvent());
    eventBus.fire(ResetMoneyEvent());
  }

  @override
  void dispose() {
    _openidController?.close();
    _cilkeLoginController?.close();
    _loginController?.close();
    _adduserController?.close();
  }
}
